package com.greenantmall.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.greenantmall.AntHomeApplication;
import com.greenantmall.R;
import com.greenantmall.adapter.GoodsListAdapterForImageItem;
import com.greenantmall.adapter.GoodsListAdapterForTradeStyleLeft;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.UIGoods;
import com.greenantmall.bean.UIGoodsList;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.UtilTools;
import com.greenantmall.view.MSpinner;
import com.lsarah.utils.SystemBarTintManager;

public class GoodsListTradeStyleActivity extends BaseActivity implements
		RetrieveDataListener {
	public static String KEY_GOODS_STYLES_LIST = "key_goods_styles_list";
	public static String KEY_GOODS_STYLES_STORE_ID = "key_goods_styles_store_id";

	private View mBackView;
	private View mBasketView;
	private TextView mBasketNumTv;
	private MSpinner mMSpinnerCategory;
	private TextView mTvSalesVolume;
	private TextView mTvPrice;
	private TextView mTvNew;

	private ViewPager mViewPager;
	private ProgressBar mProgressBar;
	private TextView mTvPrompt;

	private List<UIGoods> mDataList;
	private List<ShoppingCart> mShoppingCartList = new ArrayList<ShoppingCart>();
	private LeftLayoutManager mLeftLayoutManager;
	private RightLayoutManager mRightLayoutManager;
	private LayoutInflater mLayoutInflater;
	private View mViewLayoutLeft;
	private View mViewLayoutRight;

	private int mTotalCount = 0;
	private boolean isLoadingData = false;
	private int mCurrentOrderBy = 0;

	private String mStoreId;
	private ArrayList<String> mGoodsStylesNameList;
	private String mCurrentGoodsStylesName;

	private OnClickListener mOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (v.equals(mBackView)) {
				GoodsListTradeStyleActivity.this.finish();
			} else if(v.equals(mBasketView)) {
				if(AVUser.getCurrentUser() == null) {
					Intent intent = new Intent(GoodsListTradeStyleActivity.this, LoginActivity.class);
					startActivity(intent);
				}
				else {
					if(TextUtils.isEmpty(mStoreId)) {
						Intent intent = new Intent(GoodsListTradeStyleActivity.this, ShoppingCartActivity.class);
						startActivity(intent);
					}
					else {
						Intent intent = new Intent(GoodsListTradeStyleActivity.this, ShoppingCartActivity.class);
						intent.putExtra(ShoppingCartActivity.KEY_SP_SHOPPING_CART, false);
						intent.putExtra(ShoppingCartActivity.KEY_STORE_ID, mStoreId);
						startActivity(intent);
					}
				}
			} else if (v.equals(mMSpinnerCategory)) {
				if(mViewPager.getCurrentItem() == 0) {
					mViewPager.setCurrentItem(1);
				}
				else {
					mViewPager.setCurrentItem(0);
				}
			} else if (!TextUtils.isEmpty(mCurrentGoodsStylesName)) {
				if (v.equals(mTvSalesVolume)) {
					if (isLoadingData) {
						return;
					}
					isLoadingData = true;

					mTvSalesVolume.setSelected(true);
					mTvPrice.setSelected(false);
					mTvNew.setSelected(false);
					mTvSalesVolume.setTextColor(getResources().getColor(
							R.color.green));
					mTvPrice.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));
					mTvNew.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));

					mCurrentOrderBy = 0;
					int start = 0;
					int expectedCount = 30;
					int requestId = start;
					RetrieveDataAsyn.getInstance().getGoodsListByCategory(
							mCurrentGoodsStylesName, start, expectedCount,
							AntHomeApplication.sectionNum, mCurrentOrderBy, mStoreId,requestId,
							GoodsListTradeStyleActivity.this);
					mProgressBar.setVisibility(View.VISIBLE);
					mTvPrompt.setVisibility(View.GONE);
				} else if (v.equals(mTvPrice)) {
					if (isLoadingData) {
						return;
					}
					isLoadingData = true;

					mTvSalesVolume.setSelected(false);
					mTvPrice.setSelected(true);
					mTvNew.setSelected(false);
					mTvSalesVolume.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));
					mTvPrice.setTextColor(getResources()
							.getColor(R.color.green));
					mTvNew.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));

					mCurrentOrderBy = 1;
					int start = 0;
					int expectedCount = 30;
					int requestId = start;
					RetrieveDataAsyn.getInstance().getGoodsListByCategory(
							mCurrentGoodsStylesName, start, expectedCount,
							AntHomeApplication.sectionNum,mCurrentOrderBy, mStoreId, requestId,
							 GoodsListTradeStyleActivity.this);
					mProgressBar.setVisibility(View.VISIBLE);
					mTvPrompt.setVisibility(View.GONE);
				} else if (v.equals(mTvNew)) {
					if (isLoadingData) {
						return;
					}
					isLoadingData = true;

					mTvSalesVolume.setSelected(false);
					mTvPrice.setSelected(false);
					mTvNew.setSelected(true);
					mTvSalesVolume.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));
					mTvPrice.setTextColor(getResources().getColor(
							android.R.color.tab_indicator_text));
					mTvNew.setTextColor(getResources().getColor(R.color.green));

					mCurrentOrderBy = 2;
					int start = 0;
					int expectedCount = 30;
					int requestId = start;
					RetrieveDataAsyn.getInstance().getGoodsListByCategory(
							mCurrentGoodsStylesName, start, expectedCount,
							AntHomeApplication.sectionNum, mCurrentOrderBy, mStoreId, requestId,
							GoodsListTradeStyleActivity.this);
					mProgressBar.setVisibility(View.VISIBLE);
					mTvPrompt.setVisibility(View.GONE);
				}
			}
		}
	};

	private PagerAdapter mPagerAdapter = new PagerAdapter() {

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			if (position == 0) {
				((ViewPager) container).removeView(mViewLayoutLeft);
			} else if (position == 1) {
				((ViewPager) container).removeView(mViewLayoutRight);
			}
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View layoutView = null;
			if (position == 0) {
				((ViewPager) container).addView(mViewLayoutLeft,
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				layoutView = mViewLayoutLeft;
			} else if (position == 1) {
				((ViewPager) container).addView(mViewLayoutRight,
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				layoutView = mViewLayoutRight;
			}

			return layoutView;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			return 2;
		}
	};
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Const.SHOPPING_CART_CHANGED)) {
				refreshShoppingCartList();
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		SystemBarTintManager.setContentView(this,
				R.layout.goods_list_trade_style,
				getResources().getColor(R.color.green));

		mLayoutInflater = LayoutInflater.from(GoodsListTradeStyleActivity.this);
		mViewLayoutLeft = mLayoutInflater.inflate(
				R.layout.goods_list_trade_style_left, null);
		mViewLayoutRight = mLayoutInflater.inflate(
				R.layout.goods_list_trade_style_right, null);

		mBackView = findViewById(R.id.goods_list_trade_style_top_arrow_left);
		mBasketView = findViewById(R.id.goods_list_trade_style_shop_basket);
		mBasketNumTv = (TextView)findViewById(R.id.goods_list_trade_style_shop_basket_num);
		mMSpinnerCategory = (MSpinner) findViewById(R.id.goods_list_trade_style_mspinner_category);
		mTvSalesVolume = (TextView) findViewById(R.id.goods_list_trade_style_tv_sales_volume);
		mTvPrice = (TextView) findViewById(R.id.goods_list_trade_style_tv_price);
		mTvNew = (TextView) findViewById(R.id.goods_list_trade_style_tv_new);
		mViewPager = (ViewPager) findViewById(R.id.goods_list_trade_style_view_pager);
		mProgressBar = (ProgressBar) findViewById(R.id.goods_list_trade_style_prgressbar);
		mTvPrompt = (TextView) findViewById(R.id.goods_list_trade_style_tv_prompt);

		mMSpinnerCategory.setEnabled(false);
		mMSpinnerCategory.setOnClickListener(mOnClickListener);
		mViewPager.setAdapter(mPagerAdapter);
		mBackView.setOnClickListener(mOnClickListener);
		mBasketView.setOnClickListener(mOnClickListener);
		mTvSalesVolume.setOnClickListener(mOnClickListener);
		mTvPrice.setOnClickListener(mOnClickListener);
		mTvNew.setOnClickListener(mOnClickListener);
		mMSpinnerCategory.setHint(getResources().getString(
				R.string.goods_list_category));
		mMSpinnerCategory.setArrowIcon(R.drawable.drop_down_arrow_normal);
		
		IntentFilter filter = new IntentFilter(Const.SHOPPING_CART_CHANGED);
        this.registerReceiver(mReceiver, filter);

		// read store id
		mStoreId = getIntent().getStringExtra(KEY_GOODS_STYLES_STORE_ID);
		mStoreId = (mStoreId==null ? "" : mStoreId);
		// read mGoodsStylesNameList from intent
		mGoodsStylesNameList = getIntent().getStringArrayListExtra(
				KEY_GOODS_STYLES_LIST);
		if (mGoodsStylesNameList == null || mGoodsStylesNameList.size() == 0) {
			mProgressBar.setVisibility(View.GONE);
			mTvPrompt.setVisibility(View.VISIBLE);
			mTvPrompt.setText(R.string.goods_list_no_goods);
		} else {
			mDataList = new ArrayList<UIGoods>();
			mRightLayoutManager = new RightLayoutManager();
			mLeftLayoutManager = new LeftLayoutManager();
			mCurrentGoodsStylesName = mGoodsStylesNameList.get(0);
			mMSpinnerCategory.setText(mCurrentGoodsStylesName);
			mTvSalesVolume.performClick();
		}
		
		refreshShoppingCartList();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mReceiver);
	}
	
	@Override
	public void dataRetrieved(int requestId, Object data) {
		if (data != null) {
			UIGoodsList uiGoodsList = (UIGoodsList) data;

			if (requestId == 0) {
				mDataList.clear();
				mTotalCount = uiGoodsList.getTotalNum();
				Log.d("CEXX", "GoodsListTradeStyleActivity => dataRetrieved => mTotalCount : " + mTotalCount);
				mDataList.addAll(uiGoodsList.getUIGoodsList());
				mRightLayoutManager.mAdapter.notifyDataSetInvalidated();
				mLeftLayoutManager.mGoodsListAdapterForTradeStyleLeft
						.notifyDataSetInvalidated();
			} else {
				mDataList.addAll(uiGoodsList.getUIGoodsList());
				mRightLayoutManager.mAdapter.notifyDataSetChanged();
				mLeftLayoutManager.mGoodsListAdapterForTradeStyleLeft
						.notifyDataSetChanged();
			}

			isLoadingData = false;
			if (mDataList.size() == 0) {
				mProgressBar.setVisibility(View.GONE);
				mTvPrompt.setVisibility(View.VISIBLE);
				mTvPrompt.setText(R.string.goods_list_no_goods);
			} else {
				mProgressBar.setVisibility(View.GONE);
				mTvPrompt.setVisibility(View.GONE);
			}
		}
	}
	
	private void refreshShoppingCartList() {
		mShoppingCartList.clear();
		List<ShoppingCart> scList = UtilTools.getShoppingCartDatas();
		if(scList != null) {
			mShoppingCartList.addAll(scList);
		}
		
		int size = mShoppingCartList.size();
		if(size == 0) {
			mBasketNumTv.setVisibility(View.GONE);
		}
		else {
			mBasketNumTv.setVisibility(View.VISIBLE);
			mBasketNumTv.setText(String.valueOf(size));
		}
		
		if(mLeftLayoutManager != null && mLeftLayoutManager.mGoodsListAdapterForTradeStyleLeft != null) {
			mLeftLayoutManager.mGoodsListAdapterForTradeStyleLeft.notifyDataSetChanged();
		}
		
		if(mRightLayoutManager != null && mRightLayoutManager.mAdapter != null) {
			mRightLayoutManager.mAdapter.notifyDataSetChanged();
		}
	}

	private class LeftLayoutManager implements OnItemClickListener,
			OnScrollListener {
		private ListView mListViewLeft;
		private GridView mGridViewLeft;
		private ListViewLeftAdapter mListViewLeftAdapter;
		private GoodsListAdapterForTradeStyleLeft mGoodsListAdapterForTradeStyleLeft;

		public LeftLayoutManager() {
			mListViewLeft = (ListView) mViewLayoutLeft
					.findViewById(R.id.goods_list_trade_style_left_listview);
			mListViewLeft.setOnItemClickListener(this);
			mListViewLeftAdapter = new ListViewLeftAdapter();
			mListViewLeft.setAdapter(mListViewLeftAdapter);

			mGridViewLeft = (GridView) mViewLayoutLeft
					.findViewById(R.id.goods_list_trade_style_left_gridview);
			mGridViewLeft.setOnItemClickListener(this);
			mGoodsListAdapterForTradeStyleLeft = new GoodsListAdapterForTradeStyleLeft(
					GoodsListTradeStyleActivity.this, mDataList, mShoppingCartList);
			mGridViewLeft.setAdapter(mGoodsListAdapterForTradeStyleLeft);
			mGridViewLeft.setOnScrollListener(this);
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (parent.equals(mListViewLeft)) {
				if (isLoadingData) {
					return;
				}
				isLoadingData = true;
				
				mCurrentGoodsStylesName = mGoodsStylesNameList.get(position);
				mMSpinnerCategory.setText(mCurrentGoodsStylesName);
				mListViewLeftAdapter.notifyDataSetChanged();

				int start = 0;
				int expectedCount = 30;
				int requestId = start;
				RetrieveDataAsyn.getInstance().getGoodsListByCategory(
						mCurrentGoodsStylesName, start, expectedCount,
						AntHomeApplication.sectionNum,mCurrentOrderBy, mStoreId, requestId,
						 GoodsListTradeStyleActivity.this);
				mProgressBar.setVisibility(View.VISIBLE);
				mTvPrompt.setVisibility(View.GONE);
			} else if (parent.equals(mGridViewLeft)) {
				Log.d("CEXX",
						"CEXX ---> GoodsListActivity ---> onItemClick ---> position : "
								+ position);
//				UIGoods uiGoods = mDataList.get(position);
//				Intent intent = new Intent(GoodsListTradeStyleActivity.this,
//						DetailActivity.class);
//				intent.putExtra(DetailActivity.KEY_DETAIL_OBJECTID,
//						uiGoods.getObjectId());
//				GoodsListTradeStyleActivity.this.startActivity(intent);
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (totalItemCount >= mTotalCount) {
				return;
			}

			if (isLoadingData) {
				return;
			}

			if (firstVisibleItem + visibleItemCount < totalItemCount) {
				return;
			}
			
			isLoadingData = true;
			int start = totalItemCount;
			int expectedCount = 18;
			int requestId = start;
			RetrieveDataAsyn.getInstance().getGoodsListByCategory(
					mCurrentGoodsStylesName, start, expectedCount,
					AntHomeApplication.sectionNum, mCurrentOrderBy, mStoreId,requestId,
					GoodsListTradeStyleActivity.this);
		}

		public class ListViewLeftAdapter extends BaseAdapter {

			@Override
			public int getCount() {
				if (mGoodsStylesNameList != null) {
					return mGoodsStylesNameList.size();
				}
				return 0;
			}

			@Override
			public Object getItem(int arg0) {
				return arg0;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View child = convertView;
				ViewHolder holder = null;
				if (child == null) {
					child = mLayoutInflater.inflate(
							R.layout.goods_list_trade_style_left_listview_item,
							null);
					holder = new ViewHolder(child);
					child.setTag(holder);
				} else {
					holder = (ViewHolder) child.getTag();
				}

				String name = mGoodsStylesNameList.get(position);
				holder.getTvName().setText(name);
				if (name.equals(mCurrentGoodsStylesName)) {
					holder.getViewLine().setBackgroundResource(R.color.green);
				} else {
					holder.getViewLine().setBackgroundResource(
							android.R.color.transparent);
				}

				return child;
			}

			private class ViewHolder {
				private View mContentView;
				private TextView mTvName;
				private View mViewLine;

				public ViewHolder(View contentView) {
					mContentView = contentView;
				}

				public TextView getTvName() {
					if (mTvName == null) {
						mTvName = (TextView) mContentView
								.findViewById(R.id.goods_list_trade_style_left_listview_item_name);
					}
					return mTvName;
				}

				public View getViewLine() {
					if (mViewLine == null) {
						mViewLine = mContentView
								.findViewById(R.id.goods_list_trade_style_left_listview_item_line);
					}
					return mViewLine;
				}
			}
		}
	}

	private class RightLayoutManager implements OnItemClickListener,
			OnScrollListener {
		private GridView mGridViewRight;
		private GoodsListAdapterForImageItem mAdapter;

		public RightLayoutManager() {
			mGridViewRight = (GridView) mViewLayoutRight
					.findViewById(R.id.goods_list_trade_style_right_gridview);
			mAdapter = new GoodsListAdapterForImageItem(
					GoodsListTradeStyleActivity.this, mDataList, mShoppingCartList);
			mGridViewRight.setAdapter(mAdapter);
			mGridViewRight.setOnScrollListener(this);
			mGridViewRight.setOnItemClickListener(this);
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Log.d("CEXX",
					"CEXX ---> GoodsListActivity ---> onItemClick ---> position : "
							+ position);
//			UIGoods uiGoods = mDataList.get(position);
//			Intent intent = new Intent(GoodsListTradeStyleActivity.this,
//					DetailActivity.class);
//			intent.putExtra(DetailActivity.KEY_DETAIL_OBJECTID,
//					uiGoods.getObjectId());
//			GoodsListTradeStyleActivity.this.startActivity(intent);
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (totalItemCount >= mTotalCount) {
				return;
			}

			if (isLoadingData) {
				return;
			}

			if (firstVisibleItem + visibleItemCount < totalItemCount) {
				return;
			}
			
			isLoadingData = true;
			int start = totalItemCount;
			int expectedCount = 18;
			int requestId = start;
			RetrieveDataAsyn.getInstance().getGoodsListByCategory(
					mCurrentGoodsStylesName, start, expectedCount,
					AntHomeApplication.sectionNum, mCurrentOrderBy, mStoreId,requestId,
					GoodsListTradeStyleActivity.this);
		}

	}
}
